<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;
use \Exception;

class ZlActivePrizeNumIncRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_active_prize_num_inc_record';

    protected $cacheModel = 'prize.user_prize_inc_record';

    /**
     * 获取用户今日任务完成增加抽奖次数情况
     * @param int $uid
     * @param int $activeId
     * @param int $date
     * @return array|bool|mixed|string
     * @throws Exception
     */
    public function getUserTaskCompletionDetailsToday(int $uid, int $activeId, int $date)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('task_completion_today', "{$uid}:{$date}:{$activeId}")
            ->getDataAndSet(function () use ($uid, $date, $activeId)
            {
                try
                {
                    // task_type 任务类型 1每日任务 2消费任务
                    $data1 = $this->where(['active_id' => $activeId, 'uid' => $uid, 'task_type' => 1, 'date' => $date])->group('task_id')->column('sum(inc)', 'task_id');
                    $data2 = $this->where(['active_id' => $activeId, 'uid' => $uid, 'task_type' => 2])->group('task_id')->column('sum(inc)', 'task_id');

                    $data = $data1 + $data2;
                }
                catch (Exception $e)
                {
                    $data = [];
                    Log::write("获取用户今日任务完成情况失败；活动ID：{$activeId}用户ID：{$uid}日期：{$date};错误信息: . {$e->getMessage()}；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
                }
                return $data;
            }, [], 'task_completion_today');
    }

    /**
     * 购买商品判断是否在活动中 如果在 则完成任务
     * @param $uid
     * @param $gid
     * @param $orderNum
     * @throws Exception
     */
    public function goodsTask(int $uid, $gid, string $orderNum): void
    {
        $time = time();
        $taskConfig = config('boxactive');

        foreach ($taskConfig as $activeId => $taskConfigItem)
        {
            // 判断 在活动进行中
            if ($time >= $taskConfigItem['start_time'] && $time < $taskConfigItem['end_time'] && isset($taskConfigItem['task']['goods_task'][$gid]))
            {   //  当前购买的商品 参与活动
                $this->userDoTheTask($uid, $activeId, $taskConfigItem['task']['goods_task'][$gid], (int)$gid, $orderNum);
            }
        }
    }

    /**
     * 用户做任务
     * @param int $uid
     * @param int $activeId
     * @param int $taskId
     * @param int $gid
     * @param string $orderNum
     * @return array
     * @throws Exception
     */
    public function userDoTheTask(int $uid, int $activeId, int $taskId, int $gid = 0, string $orderNum = ''): array
    {
        $taskConfig = config('boxactive.' . $activeId);
        $date = (int)(date('Ymd'));
        // 获取用户今日任务完成情况
        $userTaskCompletionDetailsToday = $this->getUserTaskCompletionDetailsToday($uid, $activeId, $date);
        $userTaskIdIncNum = (int)($userTaskCompletionDetailsToday[$taskId] ?? 0); // 当前任务新增抽奖次数
        $indexTask = $taskConfig['task']['list'][$taskId]; // 获取当前任务信息
        if ($userTaskIdIncNum < $indexTask['max_num'])    // 判断是否达到任务获取抽奖次数上限
        {   // 未达上限
            $indexInc = $indexTask['task_type'] === 1 ? $indexTask['inc'] : $indexTask['inc_list'][$gid];  // 当前任务新增抽奖次数
            $incNum = $userTaskIdIncNum + $indexInc > $indexTask['max_num'] ? $indexTask['max_num'] - $userTaskIdIncNum : $indexInc; // 当前任务最多新增次数

            $activePrizrUserInfoModel = new ZlActivePrizrUserInfo();
            $activePrizrUserInfo = $activePrizrUserInfoModel->getUserPrizeInfo($uid, $activeId, ['id', 'prize_unsuc_num', 'total_prize_num']); // 获取用户剩余抽奖次数

            $updateUserPrizrUserInfo = [
                'prize_unsuc_num' => $activePrizrUserInfo['prize_unsuc_num'] + $incNum,
                'total_prize_num' => $activePrizrUserInfo['total_prize_num'] + $incNum,
            ];
            // 更新用户可抽奖次数
            $res = $activePrizrUserInfoModel->updateData($uid, $activeId, $updateUserPrizrUserInfo, $activePrizrUserInfo['id']);
            if (!$res)
            {   // 做任务失败
                return [
                    'status' => false,
                    'inc' => 0
                ];
            }
            // 写入做任务记录
            $recordData = [
                'uid' => $uid,
                'task_id' => $taskId,
                'task_name' => $indexTask['task_name'],
                'task_type' => $indexTask['task_type'],
                'active_id' => $activeId,
                'inc' => $incNum,
                'date' => $date,
                'order_num' => $orderNum,
                'create_time' => time()
            ];
            $this->save($recordData);
            // 更新今日任务完成情况
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)
                ->setCacheKeyDetail('task_completion_today', "{$uid}:{$date}:{$activeId}")
                ->setCacheInc($taskId, 'task_completion_today', $incNum);

            return [
                'status' => true,
                'inc' => $incNum
            ];
        }

        // 已达上限
        return [
            'status' => false,
            'inc' => 0
        ];
    }
}
